<!--  -->
<template>
  <div class="cycleMultiple">
    <!-- <div class="label_intro">{{ scriptItem.intro}}</div> -->
    <div v-for="(items,index) in dataForm[scriptItem.text]"
         :key="index"
         class="for-item cycle_multiple_cont">
      <div class="triggedWrap">
        <div class="Multiplelist_label">
          <div class="Multiplelist_label_header">
            <div class="label_header_lf">
              <span :class="!items.dis?'el-icon-arrow-down':'el-icon-arrow-right'"
                    style="margin-right:5px"
                    @click="openContent(items,index)"></span>
              <span class="laber_text">{{$t('statement.es')}}&nbsp;&nbsp;{{index+1}}</span>
            </div>
            <div class="label_header_rg">
              <el-button circle
                         plain
                         size="mini"
                         @click="deleteModuleItem(index)"></el-button>
            </div>
          </div>
          <div class="Multiplelist_label_content">
            <span>{{ scriptItem.beforeText }}</span>
            <el-input-number v-model="items[scriptItem.numberFields]"
                              class="inputNumber"
                              size="mini"
                              style="margin:0 5px;"
                              controls-position="right"
                              :min="scriptItem.minNumber"
                              :max="scriptItem.maxNumber"></el-input-number>
            <span>{{ scriptItem.middleText }}</span>
            <el-select v-model="items[scriptItem.dateFields]" @change="changeNumebrAndDate" size="mini" style="margin:0 5px;width:100px" :disabled="index!==0">
              <el-option
                v-for="(item,index) in scriptItem.selectList"
                :key="index"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <span>{{ scriptItem.afterText }}</span>
            <!-- <span class="font_weight"></span>
            <span>( who selected in Alert)</span> -->
            <!-- <span class="font_weight">{{formchran(items.managerList)}}.</span> -->
          </div>
        </div>
      </div>
      <div class="Multiplelist"
           v-show="!items.dis">
        <!-- <div class="Multiplelist_list">
          <div>{{ scriptItem.Threshold }}</div>
          <el-input-number v-model="items[scriptItem.numberFields]"
                           class="inputNumber"
                           size="mini"
                           controls-position="right"
                           :min="scriptItem.minNumber"
                           :max="scriptItem.maxNumber"></el-input-number>
        </div> -->

        <div v-for="(item,i) in items[scriptItem.templateMultipleText]"
             :key="i"
             class="for-item">

          <el-form :inline="true">
            <!-- action btn -->
            <!-- <el-form-item style="width:70px;">
              <el-button type="danger"
                         icon="el-icon-delete"
                         circle
                         plain
                         size="mini"
                         :disabled="i === 0 && items[scriptItem.templateMultipleText].length <= 1"
                         @click="deleteItem(i,items[scriptItem.templateMultipleText])"></el-button>
              <el-button type="primary"
                         icon="el-icon-plus"
                         circle
                         plain
                         size="mini"
                         @click="addItem(i,items[scriptItem.templateMultipleText])"></el-button>
            </el-form-item> -->
            <!-- for -->
            <!-- <el-form-item :label="scriptItem.toLabel"
                          class="Multiplelist_form_list"
                          style="display: inline-block;"
                          >
              <el-select v-model="item[scriptItem.toFields]"
                         filterable
                         clearable
                         :placeholder="scriptItem.toHint"
                         :style="{ width: `${scriptItem.toFieldsWidth}px` }"
                         @visible-change="comForLists($event, i,items[scriptItem.templateMultipleText])"
                         default-first-option>
                <el-option v-for="(o,ii) in forLists"
                           :key="ii"
                           :label="o[scriptItem.toFieldLabel]"
                           :value="o[scriptItem.toFieldValue]"></el-option>
              </el-select>
              <div class="add_message" @click="addItem(index,items[scriptItem.templateMultipleText])">Add Massage</div>
            </el-form-item> -->
            <!-- template -->
            <el-form-item class="form_list_template"
                          style="display: inline-block;"
                          :label-width="`${scriptItem.templateLabelWidth}px`">
              <!-- item[scriptItem.templateFields] -->
              <!-- <el-select v-model="dataForm[scriptItem.text + 'TemplateIds'][index + '_' + i]"
                         filterable
                         clearable
                         @change="templateIdChange($event, item, index, i)"
                         :placeholder="scriptItem.templateHint"
                         :style="{ width: `${scriptItem.templateFieldsWidth}px` }"
                         default-first-option>
                <el-option v-for="(o,ii) in selectDataObj[`${scriptItem.text}ListsOrigin`]"
                           :key="ii"
                           :label="o[scriptItem.templateFieldLabel]"
                           :value="o[scriptItem.templateFieldValue]"></el-option>
              </el-select> -->
              <el-dropdown trigger="click" style="margin-left:15px;margin-top:10px;height: 20px;"
                           @visible-change="handleDropdownOptionDisabled($event,item,items,i)"
                           @command="handleCommand">
                <span class="el-dropdown-link">
                 {{item.manager?transformatLabel(item.manager):'Select'}} <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{parentIndex:index,index:i,item:item,label:list[scriptItem.toFieldValue]}"
                                    v-for="(list,is) in item.toDataList"
                                    :disabled="list.disabled"
                                    :key="is">{{list[scriptItem.toFieldLabel]}}</el-dropdown-item>
                  <!-- <el-dropdown-item command="a">Manager Lv</el-dropdown-item> -->
                </el-dropdown-menu>
              </el-dropdown>
              <div v-for="(itemChild,iii) in scriptItem.contentType" :key="iii" class="item_template" style="margin-left:20px">
                <TypeSendMessageBcc v-if="itemChild.type ==='send-message'"
                                  :onlyShowUserList="true"
                                  :dataForm='item'
                                  :scriptItem='itemChild'>
                </TypeSendMessageBcc>
              </div>
              <div class="deleteTemplate cursor_pointer" style="margin-top:10px"
                   @click="deleteItem(i,items[scriptItem.templateMultipleText],items,index)"></div>
            </el-form-item>
          </el-form>
          <!-- :value="getTemplateContent(item)" -->
          <div class="editor_content">
            <quill-editor style="padding: 10px 0;background: #fff;"
                          :style="{width: `${comTextareaWidth}px`}"
                          label="Edwin Test 678"
                          :ref="`myTextEditor${index}${i}`"
                          @change="onMessageChange($event,item)"
                          v-model="item[scriptItem.templateFields]"
                          :options="editorOption"></quill-editor>
            <!-- <div class="insert-token">
              <el-tooltip :open-delay="1000" class="item"
                          effect="dark"
                          content="Insert a token"
                          placement="top">
                <el-popover placement="top"
                            width="205"
                            popper-class="insert_token_pop"
                            @show="tokenListShow(index)"
                            @hide="tokenListHide">
                  <el-input v-model="searchToken"
                            placeholder="search"
                            @input="getFilterTokenList"
                            size="small"
                            style="margin-bottom:10px;"></el-input>
                  <div class="token-list">
                    <div class="token-list-item"
                         v-for="(item, index) in filterTokenList"
                         :key="index">
                      <el-divider class="split-line"></el-divider>
                      <div class="group-title">{{ item.name || $store.state.bot.type }}</div>
                      <div class="group-item"
                           v-for="(its, ii) in item.fieldsList"
                           :key="ii"
                           @click="clickToken(its,index,i)">{{ its.label }}</div>
                    </div>
                  </div>
                  <el-button size="mini"
                             type="primary"
                             plain
                             slot="reference"
                             style="padding:7px;border:none;">
                    <span class="cuifont icon_insert_token"
                          style="fontSize:14px;"></span>
                  </el-button>
                </el-popover>
              </el-tooltip>
            </div> -->
            <div class="insert-token">
              <el-tooltip :open-delay="1000" class="item" effect="dark" :content="$t('statement.iat')" placement="top">
                <el-popover placement="top" trigger="click" popper-class="insert_token_pop"
                            width="380">
                  <div v-if="!isShowChild&&!isShowChildDrillThrough" style="color:#000;font-size:16px;font-weight: 600;margin-bottom:10px">{{$t('statement.dt')}}</div>
                  <div v-else class="cursor_pointer" style="color:#000;font-size:16px;font-weight: 600;margin-bottom:10px" @click="gotoback"><i class="el-icon-arrow-left"></i>&nbsp;&nbsp;{{$t('statement.fn')}}</div>
                  <el-input v-if="!isShowChild&&!isShowChildDrillThrough" v-model="searchToken"
                            prefix-icon="el-icon-search"
                            :placeholder="$t('placeholder.search')"
                            @input="getFilterTokenList"
                            size="small"
                            style="margin-bottom:10px;"></el-input>
                  <el-input v-if="isShowChild||isShowChildDrillThrough" v-model="searchTokenchild"
                            prefix-icon="el-icon-search"
                            :placeholder="$t('placeholder.search')"
                            @input="getFilterTokenchildList"
                            size="small"
                            style="margin-bottom:10px;"></el-input>
                  <div v-if="isTipsShow&&!isShowChild&&!isShowChildDrillThrough"  style="height:50px;backgroundColor:#E6F7FF;">
                    <div style="float:left;width:90%;color:#138DC7;line-height:20px;padding:5px;padding-left:9px;word-break: break-word;">{{$t('statement.adtfd')}}</div>
                    <i @click="isTipsShow=false" class="el-icon-close cursor_pointer" style="float:right;color:#138DC7;margin:8px 9px 0 0"></i>
                  </div>
                  <el-alert v-if="!(filterTokenList.length>0&&filterTokenList[0].fieldsList.length>0)&&!drillThroughFieldsListarr.length>0" style="margin-top:10px" :closable="false" center :title="$t('statement.nmd')" type="info"></el-alert>
                  <div class="token-list" v-if="filterTokenList.length>0&&filterTokenList[0].fieldsList.length>0">
                    <div class="token-list-item"
                        v-for="(item, index222) in filterTokenList"
                        :key="index222">
                      <!-- <el-divider v-if="!isShowChild" class="split-line"></el-divider> -->
                      <div v-if="!isShowChild&&!isShowChildDrillThrough">
                        <div class="group-title" style="backgroundColor:#F0F0F0;padding-left:9px;" :style="{'margin-top':isTipsShow?'10px':0}">{{$t('statement.dsf')}}</div>
                        <div style="max-height: 150px;overflow:auto">
                          <div class="group-item"
                              v-for="(its, ii) in item.fieldsList"
                              :key="ii"
                              @click="its.type === 'user' ? openChild(its) : clickToken(its,index,i)"><span :style="{'font-weight':its.type === 'user'? '600' : '400'}">{{ its.type === 'user' ? its.label.replace(/[\{\}]/g,'') : its.label}}</span>
                              <i v-if="its.type === 'user'" class="el-icon-arrow-right" style="float:right;padding-top:10px"></i>
                          </div>
                        </div>
                      </div>
                      <div v-if="isShowChild&&!isShowChildDrillThrough">
                        <div class="group-item"
                          v-for="(its,e) in filteruserfieldsList"
                            :key="e"
                            @click="clickTokenchild(its,null,index,i)">{{ its.label }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="token-list" v-if="drillThroughFieldsListarr.length>0">
                    <div class="token-list-item">
                      <div v-if="!isShowChild&&!isShowChildDrillThrough">
                        <div class="group-title" style="backgroundColor:#F0F0F0;padding-left:9px;">{{$t('statement.dtf')}}</div>
                        <div style="height: 150px;overflow:auto">
                          <div class="group-item"
                              v-for="(its, ii) in drillThroughFieldsListarr"
                              :key="ii"
                              @click="openChildDrillThrough(its,ii)"><span style="font-weight:600">{{its.datasetName}}</span>
                              <i class="el-icon-arrow-right" style="float:right;padding-top:10px"></i>
                          </div>
                        </div>
                      </div>
                      <div v-if="!isShowChild&&isShowChildDrillThrough" style="max-height:442px;overflow:auto">
                        <div class="group-item"
                          v-for="(its,ee) in childDrillThroughfieldsList"
                            :key="ee"
                            @click="clickTokenchild(its,true,index,i)">{{ its.label }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <el-button size="mini"
                            type="primary"
                            plain
                            slot="reference"
                            style="padding:7px;border:none;">
                    <span class="cuifont icon_insert_token"
                          style="fontSize:14px;"></span>
                  </el-button>
                </el-popover>
              </el-tooltip>
            </div>
            <!-- <TypeTemplate
                          :dataForm='dataForm'
                          :blockInfo='blockInfo'
                          :scriptItem='scriptItem.templateForm'></TypeTemplate> -->
            <div class="editor_content_template">
              <el-dropdown @command="handleCommandPreview($event,index,i)">
                <span class="el-dropdown-link">
                  {{item.mode || 'Light Mode'}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="lightmode">Light Mode</el-dropdown-item>
                  <el-dropdown-item command="darkmode">Dark Mode</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <div>
                <label for="">{{$t('statement.ct')}} &nbsp;</label>
                <el-select v-model="item['TemplateIds']"
                           filterable
                           clearable
                           @change="templateIdChange($event, item, index, i)"
                           :placeholder="scriptItem.templateHint"
                           default-first-option>
                  <el-option v-for="(o,ii) in filterSelect(selectDataObj[`${scriptItem.text}ListsOrigin`])"
                             :key="ii"
                             :label="o[scriptItem.templateFieldLabel]"
                             :value="o[scriptItem.templateFieldValue]"></el-option>
                </el-select>
              </div>
              <div>
                <el-popover placement="top"
                            width="205"
                            @hide="clearPopover(i)"
                            :ref="`editTemplatePopover-${index}${i}`">
                  <el-form :model="editTemplateForm"
                           :rules="dataRule"
                           size="mini"
                           ref="template-form"
                           label-position="top">
                    <el-form-item :label="$t('label.tn')"
                                  prop="name">
                      <el-input v-model="editTemplateForm.name"
                                :placeholder="$t('placeholder.pe')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('label.tt')"
                                  prop="type">
                      <!-- <el-input v-model="editTemplateForm.type"
                                placeholder="Please Select"></el-input> -->
                      <el-select v-model="editTemplateForm.type"
                                 :placeholder="$t('placeholder.ps')">
                        <el-option v-for="(its,ie) in ['teams_message','email']"
                                   :key="ie"
                                   :label="its"
                                   :value="its"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-checkbox v-model="viewTemplatePage">{{$t('statement.vaa')}}</el-checkbox>
                    </el-form-item>
                  </el-form>
                  <div class="popover-footer-btn">
                    <el-button size="mini"
                               @click="editTemplatePopoverCloese(index,i)">{{$t('attribute.close')}}</el-button>
                    <el-button size="mini"
                               type="primary"
                               :loading='addBtnLoading'
                               @click="addMessageTemplate(i,item[scriptItem.templateFields])">{{$t('attribute.add')}}</el-button>
                  </div>
                  <el-button size="mini"
                             type="primary"
                             plain
                             style="margin-right:15px;padding:7px;border:none;"
                             slot="reference">
                    <!-- <span class="cuifont icon_mail_add"
                          style="fontSize:14px;"></span> -->
                    <span class="cuifont icon_save_edit" style="fontSize:14px;"> {{$t('statement.template')}}</span>
                  </el-button>
                  <!-- <div class="cuifont icon_mail_add"
                    slot="reference"></div> -->
                </el-popover>
              </div>
            </div>
            <!-- <div v-if="item['priviewChecked']">
              <el-switch v-model="item['switchPreview']"
                         active-text=" Dark Mode"
                         inactive-text="Light Mode ">
              </el-switch>
              <div v-if="!item['switchPreview']">
                <div style="background-color:#FFFFFF;color:#1e1e1e;"
                     v-html="item['priviewMessage']"></div>
              </div>
              <div v-else>
                <div style="background-color:#292929;color:#FFFFFF;"
                     v-html="item['priviewMessage']"></div>
              </div>
            </div> -->

          </div>
        </div>
        <div class="Multiplelist_form_list">
          <!-- <div>
            <span>{{scriptItem.toLabel}}</span>
            <el-select v-model="items[scriptItem.toFields]"
                       filterable
                       clearable
                       :placeholder="scriptItem.toHint"
                       default-first-option>
              <el-option v-for="(o,ii) in emailList"
                         :key="ii"
                         :label="o.teamsMail"
                         :value="o.teamsMail"></el-option>
            </el-select>
          </div> -->

          <div class="add_message"
               @click="addItem(index,items[scriptItem.templateMultipleText])"><span class="">{{$t('statement.am')}}</span></div>
        </div>
      </div>
      <!-- <div class="moduleBtn">
        <el-button type="danger"
                   icon="el-icon-delete"
                   circle
                   plain
                   size="mini"
                   :disabled="index === 0 && dataForm[scriptItem.text].length <= 1"
                   @click="deleteModuleItem(index)"></el-button>
        <el-button type="primary"
                   icon="el-icon-plus"
                   circle
                   plain
                   size="mini"
                   @click="addModuleItem(index)"></el-button>
      </div> -->
    </div>
    <div class="add_new_program">
      <el-button type="primary"
                 icon="el-icon-plus"
                 circle
                 size="mini"
                 @click="addModuleItem">{{$t('statement.an')}}</el-button>
    </div>
  </div>
</template>

<script>
import mixinTypeViewModule from '@/mixins/script-type-view-module'
import TypeTemplate from './type-select-template'
import { debounce } from 'lodash'
import TypeSendMessageBcc from './type-send-message-bcc'
// import { debounce } from 'lodash'
export default {
  mixins: [mixinTypeViewModule],
  components: { TypeTemplate, TypeSendMessageBcc },
  props: {
    blockInfo: {
      type: Object,
      default: () => {
      }
    }
  },
  data () {
    return {
      visible: false,
      priviewMessage: null,
      switchPreview: false,
      parentChangeIndex: 0,
      priviewChecked: false,
      emailList: [],
      editorOption: {
        name: '471',
        modules: {
          toolbar: [
            ['code-block'],
            [{ 'direction': 'rtl' }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ 'color': [] }],
            [{ 'background': [] }],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'font': ['sans-serif', 'monospace', 'serif'] }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'align': [] }],
            ['link'],
            ['clean']
          ]
        },
        theme: 'snow',
        placeholder: ''
      },
      forLists: this.scriptItem.toDataList || [],
      searchToken: null,
      filterTokenList: [],
      editTemplateForm: {
        name: null,
        type: null
      },
      viewTemplatePage: false,
      addBtnLoading: false,
      insertTokenPopover: false,
      editTemplatePopover: false,
      popIndex: 0,
      dataRule: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      },
      isShowChild: false,
      isTipsShow: true,
      drillThroughFieldsListarr: [],
      filteruserfieldsList: [],
      fatherfield: null,
      isShowChildDrillThrough: false,
      userfieldsList: [{ label: '{headUrl}', value: 'headUrl' },
        { label: '{email}', value: 'email' },
        { label: '{firstName}', value: 'firstName' },
        { label: '{lastName}', value: 'lastName' },
        { label: '{fullName}', value: 'fullName' } ]
    }
  },
  watch: {
    isShowChild (val) {
      if (!val) {
        this.searchTokenchild = null
        this.resetFilterTokenchildList(this.searchTokenchild)
      }
    },
    isShowChildDrillThrough (val) {
      if (!val) {
        this.searchTokenchild = null
        this.resetFilterTokenchildList(this.searchTokenchild)
      }
    },
    insertTokenPopover: {
      handler: function (val) {
        if (val) {
          this.isTipsShow = true
          document.addEventListener('mousedown', this.mouseDownListener)
        } else {
          document.removeEventListener('mousedown', this.mouseDownListener)
          this.searchToken = null
          this.resetFilterTokenList(this.searchToken)
          this.searchTokenchild = null
          this.resetFilterTokenchildList(this.searchTokenchild)
          this.isShowChild = false
          this.isShowChildDrillThrough = false
        }
      },
      immediate: true
    },
    editTemplatePopover: {
      handler: function (val) {
        if (val) {
          document.addEventListener('mousedown', this.mouseDownListener)
        } else {
          document.removeEventListener('mousedown', this.mouseDownListener)
        }
      },
      immediate: true
    }
  },
  computed: {
    comScriptItem () {
      return { ...this.scriptItem, fieldLabel: this.scriptItem.templateFieldLabel, fieldValue: this.scriptItem.templateFieldValue }
    },
    comTextareaWidth () {
      try {
        let width = 70 + 20 + Number(this.scriptItem.toLabelWidth) + Number(this.scriptItem.toFieldsWidth) + Number(this.scriptItem.templateLabelWidth) + Number(this.scriptItem.templateFieldsWidth)
        return width
      } catch (error) {
        return 'auto'
      }
    }

  },
  created () {
    let _self = this
    try {
      _self.dataForm[_self.scriptItem.text].forEach(item => {
        if (!item[_self.scriptItem['dateFields']]) {
          _self.$set(item, _self.scriptItem['dateFields'], _self.dataForm[_self.scriptItem['dateFields']] || 'day')
        }
      })
    } catch (error) {

    }
    this.getTokenList()
    this.filteruserfieldsList = this.userfieldsList
  },
  methods: {
    changeNumebrAndDate () {
      this.$forceUpdate()
      this.dataForm[this.scriptItem.text].forEach((item, index) => {
        if (index !== 0) {
          item[this.scriptItem.dateFields] = this.dataForm[this.scriptItem.text][0][this.scriptItem.dateFields]
        }
      })
    },
    handleCommandPreview (e, index, i) {
      let f = document.querySelectorAll('.cycle_multiple_cont')[index]
      if (e === 'darkmode') {
        f.querySelectorAll('.ql-container')[i].classList.remove('lightmode')
        f.querySelectorAll('.ql-container')[i].classList.add('darkmode')
      } else {
        f.querySelectorAll('.ql-container')[i].classList.remove('darkmode')
        f.querySelectorAll('.ql-container')[i].classList.add('lightmode')
      }
    },
    clickTokenchild (its, isDrillThrough, index, i) {
      if (isDrillThrough) {
        this.insertFields(`${this.fatherfield}#${its.value}`, index, i)
      } else {
        this.insertFields(`${this.fatherfield}.${its.value}`, index, i)
      }
    },
    mouseDownListener (event) {
      if (!event.target.closest('.block-model-dialog')) {
      } else {
        this.insertTokenPopover = false
        this.editTemplatePopover = false
      }
    },
    openChildDrillThrough (its, index) {
      this.fatherfield = its.datasetName
      this.isShowChildDrillThrough = true
      this.childDrillThroughfieldsListarr = this.drillThroughFieldsListarr[index].data
      this.childDrillThroughfieldsList = this.childDrillThroughfieldsListarr
    },
    getFilterTokenList: debounce(function (val) {
      this.resetFilterTokenList(val)
    }, 800),
    getFilterTokenchildList: debounce(function (val) {
      this.resetFilterTokenchildList(val)
    }, 800),
    clickToken (its, index, i) {
      // if (!(this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`].find(item => item.field === its.value))) {
      //   this.dataForm[`${this.scriptItem.datasetKeyStore}UseFidld`].push({
      //     field: its.value,
      //     dbType: its.type
      //   })
      // }
      this.insertFields(its.value, index, i)
    },
    resetFilterTokenchildList (val) {
      let searchVal = val || this.searchTokenchild
      if (searchVal) {
        let copyData = this._.cloneDeep(this.userfieldsList)
        copyData = copyData.filter(its => its.label.toLowerCase().includes(searchVal.toLowerCase()))
        this.filteruserfieldsList = copyData
      } else {
        this.filteruserfieldsList = this.userfieldsList
      }
      if (searchVal) {
        let copyData = this._.cloneDeep(this.childDrillThroughfieldsListarr)
        copyData = copyData.filter(its => its.label.toLowerCase().includes(searchVal.toLowerCase()))
        this.childDrillThroughfieldsList = copyData
      } else {
        this.childDrillThroughfieldsList = this.childDrillThroughfieldsListarr
      }
    },
    openChild (its) {
      this.fatherfield = its.value
      this.isShowChild = true
    },
    gotoback () {
      this.isShowChild = false
      this.isShowChildDrillThrough = false
    },
    filterSelect (arr) {
      if (!arr) {
        arr = []
      }
      var temp = arr.filter(item => {
        return item.name.includes('Escalation-')
      })
      temp = temp.sort(function (a, b) {
        return a.name.length - b.name.length
      })
      temp = temp.sort(function (a, b) {
        if (a.name.length === b.name.length) {
          return a.name.localeCompare(b.name)
        }
      })
      return temp
    },
    onMessageChange (e, item) {
      if (e) {
        item['priviewMessage'] = e.html
      }
      this.$forceUpdate()
    },
    formchran (str) {
      let arr = str.split(',')
      let returnStr = []
      this.scriptItem.defaultValue[0].templateList[0].toDataList.forEach(element => {
        if (arr.includes(element.value)) returnStr.push(element.label)
      })
      return returnStr.join(' , ')
    },
    editTemplateReturn (i) {
      // return `editTemplatePopover${i}`
      this.$set(this, `editTemplatePopover${i}`, false)
      return this[`editTemplatePopover${i}`]
      // return `editTemplatePopover`
    },
    editTemplatePopoverCloese (index, i) {
      this.$refs[`editTemplatePopover-${index}${i}`][0].doClose()
    },
    addMessageTemplate (index, ItemTemplate) {
      this.$refs['template-form'][index].validate((valid) => {
        if (!valid) {
          return false
        }
        this.addBtnLoading = true
        const params = {
          template: ItemTemplate || '',
          ...this.editTemplateForm
        }
        this.$interface.schedule.saveTemplateInfoApi(params)
          .then(({ data: res }) => {
            this.addBtnLoading = false
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$message.success(res.msg)
            this.editTemplatePopover = false
            this.init()
            this.viewTemplatePage && this.routerToTemplatePage()
          }).catch(() => {
            this.addBtnLoading = false
          })
      })
    },
    clearPopover (index) {
      this.$refs['template-form'][index].resetFields()
      this.viewTemplatePage = false
    },
    // insertFields (value, index, i) {
    //   if (!value) {
    //     return false
    //   }
    //   const quillSelf = this.$refs[`myTextEditor${this.popIndex}${i}`][0].quill
    //   quillSelf.focus()
    //   value = ` {${value}}`
    //   let selection = quillSelf.getSelection()
    //   let nowIndex = 0
    //   if (selection) {
    //     nowIndex = selection.index
    //   }
    //   quillSelf.insertText(nowIndex, value, {
    //     'color': '#17B3A3',
    //     'bold': true
    //   })

    //   setTimeout(() => {
    //     quillSelf.insertText(quillSelf.getSelection(), ' ', {
    //       'color': '#000000',
    //       'bold': false
    //     })
    //   }, 0)
    // },
    insertFields (value, index, i) {
      if (!value) {
        return false
      }
      const quillSelf = this.$refs[`myTextEditor${index}${i}`][0].quill
      quillSelf.focus()
      let selection = quillSelf.getSelection()
      let nowIndex = 0
      if (selection) {
        nowIndex = selection.index
      }
      /* ===================== MB-15085 START ===================== */
      // quillSelf.insertText(nowIndex, value, {
      //   'color': '#17B3A3',
      //   'bold': true
      // })
      quillSelf.clipboard.dangerouslyPasteHTML(nowIndex, `<span>&nbsp;&nbsp;</span><strong style="color:#17B3A3">{${value}}</strong><span>&nbsp;&nbsp;</span>`)
      /* ===================== MB-15085 END ===================== */
    },
    getTokenList () {
      let id = this.$store.state.bot.id
      let type = this.$store.state.bot.type
      this.tokenList = []
      if (!id) {
        return
      }
      const params = {}
      type === 'dataset' && (params['datasetId'] = id)
      type === 'widget' && (params['gadgetId'] = id)
      params.showColumn = true
      this.$interface.reports.getFieldsListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.tokenList = []
            return false
          }
          if (res.querySelectedColumns) {
            this.dataForm.resultValue = res.querySelectedColumns
            this.drillThroughFieldsList = res.querySelectedColumns
            this.drillThroughFieldsList.forEach(item => {
              item.data.forEach(its => {
                its.label = `{${its.alias}}`
                its.value = its.alias
              })
            })
            this.drillThroughFieldsListarr = this.drillThroughFieldsList
          }
          let tempList = []
          res.data.forEach(item => {
            if (item.type === 'user') {
              tempList.unshift({
                label: `{${item.name}}`,
                value: item.name,
                type: item.type
              })
            } else {
              tempList.push({
                label: `{${item.name}}`,
                value: item.name,
                type: item.type
              })
            }
          })
          this.tokenList.push({
            name: this.$store.state.bot.name,
            fieldsList: tempList
          })
          this.$nextTick(() => {
            this.resetFilterTokenList()
          })
        }).catch(() => {
          this.tokenList = []
        })
    },
    tokenListHide () {
      this.searchToken = ''
    },
    tokenListShow (index) {
      this.popIndex = index
    },
    resetFilterTokenList (val) {
      let searchVal = val || this.searchToken
      if (searchVal) {
        let copyData = this._.cloneDeep(this.tokenList)
        for (let i = 0; i < copyData.length; i++) {
          copyData[i].fieldsList = copyData[i].fieldsList.filter(its => its.label.toLowerCase().includes(searchVal.toLowerCase()))
        }
        this.filterTokenList = copyData || []
      } else {
        this.filterTokenList = this.tokenList || []
      }
      if (searchVal) {
        let copyData = JSON.parse(JSON.stringify(this.drillThroughFieldsList))
        copyData = copyData.filter(its => its.datasetName.toLowerCase().includes(searchVal.toLowerCase()))
        this.drillThroughFieldsListarr = copyData || []
      } else {
        this.drillThroughFieldsListarr = this.drillThroughFieldsList || []
      }
    },
    returnAllManager (item) {
      item.managerList = ''
      let str = ''
      item[this.scriptItem.templateMultipleText].forEach(element => {
        if (element.manager) str += element.manager + ','
      })
      this.$set(item, 'managerList', str)
    },
    handleCommand (command) {
      this.parentChangeIndex = command.parentIndex
      this.$set(this.dataForm[this.scriptItem.text][command.parentIndex][this.scriptItem.templateMultipleText][command.index], 'manager', command.label)
      this.$set(this.dataForm[this.scriptItem.text][command.parentIndex][this.scriptItem.templateMultipleText][command.index], 'disabled', true)
      this.returnAllManager(this.dataForm[this.scriptItem.text][command.parentIndex])
    },
    transformatLabel (manager) {
      let label = ''
      switch (manager) {
        case 'user':
          label = 'User'
          break
        case 'manager':
          label = 'Manager'
          break
        case 'managerLevel2':
          label = 'Manager Level 2'
          break
        case 'managerLevel3':
          label = 'Manager Level 3'
          break
        default:
          label = 'Select'
      }
      return label
    },
    handleDropdownOptionDisabled (e, item, items, index) {
      if (e) {
        let mangerList = []
        items.templateList.forEach((element, i) => {
          if (index !== i) mangerList.push(element.manager)
        })
        item.toDataList.forEach(element => {
          if (mangerList.includes(element.value)) {
            element.disabled = true
          }
          if (!(mangerList.includes(element.value))) {
            element.disabled = false
          }
        })
      }
    },
    initDropdownOptionDisabled (selfItem, items, index) {
      items.forEach((element, i) => {

      })
    },
    openContent (list, index) {
      if (list.hasOwnProperty('dis') && list.dis) { this.$set(list, 'dis', false) } else this.$set(list, 'dis', true)
    },
    templateIdChange (val, item, index, i) {
      item['TemplateIds'] = val
      item[this.scriptItem.templateFields] = this.selectDataObj[`${this.scriptItem.text}ListsOrigin`].find(e => e[this.scriptItem.templateFieldValue] === val).template
    },
    addItem (index, obj) {
      if (obj.length < 3) {
        let a = []
        let temp = JSON.parse(JSON.stringify({ ...this.scriptItem.defaultValue[0] }))
        obj.forEach(element => {
          a.push(element.manager)
        })
        temp[this.scriptItem.templateMultipleText][0].toDataList.forEach(element => {
          if (a.includes(element.value)) element.disabled = true
        })
        obj.push(temp[this.scriptItem.templateMultipleText][0])
      }
    },
    deleteItem (i, obj, items, index) {
      obj.splice(i, 1)
      this.returnAllManager(items)
    },
    getTemplateContent (item) {
      try {
        return this.selectDataObj[`${this.scriptItem.text}ListsOrigin`].find(e => e[this.scriptItem.templateFieldValue] === item[this.scriptItem.templateFields]).template
      } catch (error) {
        return null
      }
    },
    comForLists (e, index, obj) {
      if (!e) {
        return false
      }
      let lastList = []
      let selectedList = obj || []
      let originList = this.scriptItem.toDataList || []
      if (Array.isArray(selectedList)) {
        for (let j = 0; j < originList.length; j++) {
          const originItem = originList[j]
          if (selectedList.findIndex(e => e[this.scriptItem.toFields] === originItem[this.scriptItem.toFieldValue]) === -1) {
            lastList.push(originItem)
          }
        }
      }
      try {
        if (selectedList[index][this.scriptItem.toFields]) {
          let temp = originList.find(e => selectedList[index][this.scriptItem.toFields] === e[this.scriptItem.toFieldValue])
          temp && lastList.push(temp)
        }
      } catch (error) { }
      this.forLists = lastList
    },
    addModuleItem (index) {
      let itemTemp = JSON.parse(JSON.stringify({ ...this.scriptItem.defaultValue[0] }))
      itemTemp.templateList[0].TemplateIds = ''
      itemTemp.templateList[0].templateContent = '';
      this.dataForm[this.scriptItem.text][0]&&(itemTemp[this.scriptItem.dateFields] = this.dataForm[this.scriptItem.text][0][this.scriptItem.dateFields]);
      this.dataForm[this.scriptItem.text].push(itemTemp)
    },
    deleteModuleItem (index) {
      this.dataForm[this.scriptItem.text].splice(index, 1)
    }
  }
}
</script>

<style lang='scss'>
.cycleMultiple {
  .cycle_multiple_cont {
    background: #ffffff;
    box-shadow: 1px 2px 8px -1px rgba(158, 158, 158, 0.15);
    border-radius: 4px;
    border: 1px solid rgba(19, 141, 199, 0.02);
    padding: 10px;
  }
  .Multiplelist_list {
    margin-bottom: 10px;
    padding-bottom: 10px;
    box-shadow: 0px 1px 0px 0px #f0f0f0;
    width: 100%;
  }
  .editor_content {
    position: relative;
    background: #f0f0f0;
    border-radius: 0 0 6px 6px;
    padding: 10px;
    padding-top: 0;
    ::v-deep .ql-snow {
      border: 0;
    }
    .ql-toolbar {
      border-bottom: 1px solid #ccc;
    }
    .quill-editor {
      background-color: #fff;
    }
    .editor_content_template {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
      .el-input__inner {
        background-color: transparent;
        border: 0;
        padding: 0;
      }
      input {
        border: none;
        &::-webkit-input-placeholder {
          color: $--theme-color !important;
        }
      }
    }
    .ql-snow {
      padding: 0 20px;
      & .ql-tooltip {
        z-index: 1;
        left: 10px !important;
      }
      &.ql-toolbar button,
      & .ql-toolbar button,
      & .ql-color-picker,
      & .ql-icon-picker {
        width: 14px;
        height: 14px;
        padding: 0;
        & svg {
          float: left;
        }
      }
      & .ql-picker-label {
        padding: 0;
        border: none;
        float: left;
      }
      & .ql-formats {
        margin-right: 20px;
        & button {
          margin-right: 20px;
          &:last-child {
            margin-right: 0;
          }
        }
      }
    }
    .insert-token {
      position: absolute;
      right: 20px;
      top: 15px;
      width: 30px;
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .Multiplelist_form_list {
    padding-bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .add_message {
      width: 100px;
      background: #138dc7;
      border-radius: 2px;
      font-size: 12px;
      font-weight: 400;
      color: #ffffff;
      padding: 0px 10px;
      cursor: pointer;
      line-height: 32px;
      text-align: center;
      background-image: url("../../../assets/ticket/company_watch/add_company_watch.png");
      background-repeat: no-repeat;
      background-size: 12px;
      background-position: 10px center;
    }
    ::v-deep .el-input__inner {
      border: 0;
    }
  }
  .form_list_template {
    width: 100%;
    background: #f0f0f0;
    border-radius: 6px 6px 0 0;
    padding: 7px 0;
    .el-input__inner {
      border: 0;
      background-color: transparent;
    }
    .el-form-item__content {
      display: flex;
      // justify-content: space-between;
      // align-items: center;
      // height: 40px;
      // .el-dropdown {
      //   position: absolute;
      //   left: 15px;
      // }
      .deleteTemplate {
        width: 14px;
        height: 14px;
        position: absolute;
        right: 15px;
        background: url("../../../assets/mspbots/qa-bot/delete_item_template.png");
        background-repeat: no-repeat;
        background-position: center;
        background-size: 14px;
      }
    }
  }
  .font_weight {
    font-size: 14px;
    font-weight: 600;
    color: #138dc7;
    line-height: 20px;
    margin: 0 5px;
  }
  .label_intro {
    width: 550px;
    font-size: 14px;
    font-weight: 400;
    color: #7f7f7f;
    line-height: 20px;
    margin-bottom: 10px;
  }
  .for-item {
    // border: 1px solid #dfdfdf;
    border-radius: 6px;
    // padding: 10px;
    margin-bottom: 15px;
  }
  .el-form--inline .el-form-item {
    display: inline-flex !important;
    margin-bottom: 0 !important;
  }
  .el-form-item__label {
    font-weight: normal !important;
    padding-bottom: 0;
  }
  .triggedWrap {
    margin-bottom: 10px;
    .Multiplelist_label {
      .Multiplelist_label_header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        .laber_text {
          font-size: 16px;
          font-weight: 600;
          color: rgba(0, 0, 0, 0.75);
        }
        .label_header_rg {
          background: url("../../../assets/mspbots/qa-bot/escalation_delete.png");
          background-repeat: no-repeat;
          background-size: 14px;
          background-position: center;
          background-color: transparent;
          button {
            border: 0;
            background-color: transparent;
          }
        }
      }
    }
    .Multiplelist_label_content {
      padding: 10px;
      background: #e6f7ff;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
      color: #138dc7;
      line-height: 20px;
    }
  }
  .moduleBtn {
    text-align: right;
    padding: 0 10px 10px 0;
  }
  .list {
    border-bottom: 1px solid #dfdfdf;
    border-radius: 6px;
    .for-item {
      border-bottom: 1px dashed #dfdfdf;
      padding: 10px 10px 0 10px;
      margin-bottom: 15px;
      &:last-child {
        border-bottom: none;
        margin-bottom: 0;
      }
    }
  }
  .quill-editor {
    width: 100% !important;
  }
  .add_new_program {
    button {
      width: 154px;
      height: 32px;
      background: #138dc7;
      border-radius: 2px;
      font-size: 12px;
      font-weight: 400;
      color: #ffffff;
    }
  }
}
.insert_token_pop {
  .token-list {
    max-height: 300px;
    overflow: auto;
    &-item {
      .group-title {
        color: rgba(0, 0, 0, 0.5);
        font-size: 12px;
        width: 100%;
        height: 30px;
        line-height: 30px;
        margin-top: 10px;
      }
      .group-item {
        height: 34px;
        line-height: 34px;
        padding: 0 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
        &:hover {
          background: #f5f7fa;
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
::v-deep .ql-container.darkmode {
  color: #fff;
 background-color: #292929;
}
::v-deep .ql-container.lightmode {
  color: #1e1e1e;
 background-color: #fff;
}
</style>
